# nlohmann-json.cmake
# A CMake script to fetch and manage nlohmann/json

# Guard against multiple inclusion
if(TARGET nlohmann_json)
    return()
endif()

# Allow the user to configure the version
set(NLOHMANN_JSON_VERSION "v3.11.3" CACHE STRING "Version of nlohmann/json to fetch")
set(NLOHMANN_JSON_REPO "https://github.com/nlohmann/json.git")
set(THIRD_PARTY_DIR ${CMAKE_CURRENT_SOURCE_DIR}/third_party)
set(NLOHMANN_JSON_DIR "${THIRD_PARTY_DIR}/nlohmann_json")

# Ensure the third-party directory exists
file(MAKE_DIRECTORY ${THIRD_PARTY_DIR})

# Check if the repository exists and matches the requested version
if(EXISTS ${NLOHMANN_JSON_DIR})
    execute_process(
        COMMAND git -C ${NLOHMANN_JSON_DIR} rev-parse --abbrev-ref HEAD
        OUTPUT_VARIABLE CURRENT_BRANCH
        OUTPUT_STRIP_TRAILING_WHITESPACE
    )
    if(NOT CURRENT_BRANCH STREQUAL ${NLOHMANN_JSON_VERSION})
        message(STATUS "Switching nlohmann/json to version ${NLOHMANN_JSON_VERSION}")
        execute_process(
            COMMAND git -C ${NLOHMANN_JSON_DIR} fetch --depth 1 origin ${NLOHMANN_JSON_VERSION}
            COMMAND git -C ${NLOHMANN_JSON_DIR} checkout ${NLOHMANN_JSON_VERSION}
            WORKING_DIRECTORY ${NLOHMANN_JSON_DIR}
            RESULT_VARIABLE GIT_SWITCH_RESULT
        )
        if(NOT GIT_SWITCH_RESULT EQUAL 0)
            message(FATAL_ERROR "Failed to switch nlohmann/json to version ${NLOHMANN_JSON_VERSION}")
        endif()
    else()
        message(STATUS "nlohmann/json is already at the requested version ${NLOHMANN_JSON_VERSION}")
    endif()
else()
    message(STATUS "Cloning nlohmann/json version ${NLOHMANN_JSON_VERSION} into ${NLOHMANN_JSON_DIR}")
    execute_process(
        COMMAND git clone --depth 1 --branch ${NLOHMANN_JSON_VERSION} ${NLOHMANN_JSON_REPO} ${NLOHMANN_JSON_DIR}
        WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
        RESULT_VARIABLE GIT_CLONE_RESULT
    )
    if(NOT GIT_CLONE_RESULT EQUAL 0)
        message(FATAL_ERROR "Failed to clone nlohmann/json repository")
    endif()
endif()

# Define the nlohmann_json target
add_library(nlohmann_json INTERFACE)
target_include_directories(nlohmann_json INTERFACE ${NLOHMANN_JSON_DIR}/include)
